<template>
  <!-- 底部表单页面 -->
  <van-action-sheet class="bottomActionConfig" v-model="showComponent">
    <div class="com-appraise-wrap">
      <div class="wrap-title" v-if="title">{{ type === '5' ? '举报' : title }}</div>
      <div class="form-wrap">
        <div class="form-field" v-if="showRate && type !== '5'">
          <van-rate
            class="ft22"
            color="var(--color)"
            v-if="!Number(initScore)"
			:readonly="false"
            allow-half
            v-model="score"
          />
          <van-rate
            class="ft22"
            color="var(--color)"
            v-else
            disabled
            disabled-color="var(--color)"
            allow-half
            :value="Number(initScore)"
          />
        </div>
        <div class="form-field" v-show="showInput">
          <textarea
            rows="4"
            :placeholder="type === '5' ? '举报内容' : placeholder"
            v-model="content"
          ></textarea>
        </div>
        <div class="upload" v-if="type === '2' && !isDoc && !isForum">
          <van-uploader  v-model="fileList" :before-read="beforeRead"
                         :max-size="maxPhotoSize"
                         :max-count="1"
                         :isDisu='true'
                         :after-read="afterRead" @oversize="onOversize"></van-uploader>
        </div>

        <div class="flex form-field" v-if="isOpenAnonymity == 1 && showAnonymous && type !== '5'">
          <van-checkbox-single v-model="isAnonymous" shape="square" /><span
            class="fs-14 ml10"
            >匿名</span
          >
        </div>
        <div class="flex form-field" v-if="showPublic">
          <van-checkbox-single v-model="isPublic" shape="square" /><span
            class="fs-14 ml10"
            >是否公开</span
          >
        </div>
        <div class="flex form-field" v-if="showTimePoint">
          <van-checkbox-single
            v-model="isTimePoint"
            shape="square"
            @change="timePointChange"
          /><span class="fs-14 ml10">是否显示时间驻点</span>
          <span class="video-area ml20" v-if="isTimePoint">
            <i class="video-icon dark"></i
            ><span>{{ transSecondsToTimeString(noteTime) }}</span>
          </span>
        </div>
      </div>
      <div class="btn-wrap">
        <button
          round
          type="primary"
          :disabled="!!(type == 4 || (Number(initScore)))"
          :loading="saveLoading"
          @click="save"
          >{{
            type === '5' ? '提交' : !!(type == 4 || (Number(initScore))) ? "您已评价" : saveBtnName
          }}</button
        >
      </div>
    </div>
  </van-action-sheet>
</template>

<script setup>
import {onLoad, onLaunch, onShow} from '@dcloudio/uni-app'
import {ref, onMounted, onBeforeUnmount,watch, computed, getCurrentInstance} from 'vue';
const {$api, $uniPush, $toast, $dialog, $uniRedirectTo} = getCurrentInstance().proxy;
import { beforePicUpload, parse, stringify, transSecondsToTimeString } from "@/assets/js/util";
import {useGetters} from "@/store/useFun";
import VanRate from "@/components/vant/van-rate/van-rate.vue";
import VanActionSheet from "@/components/vant/van-action-sheet/van-action-sheet.vue";
import VanUploader from "@/components/vant/van-uploader/van-uploader.vue";
import VanCheckboxSingle from "@/components/vant/van-checkbox-single/van-checkbox-single.vue";
import {sm2} from 'sm-crypto'
import {MS2_PUBLICKEY} from '@/assets/js/constant'
const cipherMode = 1 
// 定义响应式数据
const content = ref(''); // 评价内容
const score = ref(5); // 评价等级
const isAnonymous = ref(false); // 是否匿名 提交时需要转换成：（1是 2否）
const isPublic = ref(false); // 是否公开 提交时需要转换成：（1是 2否）
const isTimePoint = ref(false); // 是否显示时间驻点
const showComponent = ref(false);
const fileList = ref([]);
const maxPhotoSize = ref(10 * 1024 * 1024);

// props
const props = defineProps({
  type: {
    // 1 评价 2 讨论 3 笔记 4.打分--无需填写
    type: String,
    default: "1"
  },
  showAction: {
    type: Boolean,
    default: false
  },
  title: {
    // 标题
    type: String,
    default: ""
  },
  showRate: {
    // 是否显示评分
    type: Boolean,
    default: true
  },
  isDoc: {
    // 是否是文档
    type: Boolean,
    default: false
  },
  isForum: {
    // 是否是话题
    type: Boolean,
    default: false
  },
  showAnonymous: { // 是否显示匿名
    type: Boolean,
    default: true,
  },
  showPublic: {
    // 是否显示公开
    type: Boolean,
    default: false
  },
  showTimePoint: {
    // 是否显示时间驻点
    type: Boolean,
    default: false
  },
  noteTime: {
    type: String,
    default: ""
  },
  showInput: {
    type: Boolean,
    default: true
  },
  placeholder: {
    // 输入框占位符
    type: String,
    default: "谈谈你的看法..."
  },
  saveLoading: {
    type: Boolean,
    default: false
  },
  saveBtnName: {
    type: String,
    default: "提交评价"
  },
  initScore: {
    type: [String, Number],
    default: ""
  },
  mainServer: {
    type: Object,
    default: () => {}
  },
  inputContent: {
    type: String,
    default: ""
  },
  checkPublic: {
    type: Boolean,
    default: false
  },
});
const {isOpenAnonymity} = useGetters('siteInfo', ['isOpenAnonymity'])

onMounted(()=>{
  content.value = props.inputContent
  isPublic.value = props.checkPublic
})
// 生命周期函数
watch(() => props.showAction, (val) => {
  showComponent.value = val;
  content.value = props.inputContent;
  isPublic.value = props.checkPublic;
  if (!val) {
    content.value = '';
    isPublic.value = false;
    score.value = 5;
    isAnonymous.value = false;
    isTimePoint.value = false;
    fileList.value = [];
  }
});
watch(()=>showComponent.value, (val)=>{
  if (!val) {
    emit("hide");
  }
})
const emit = defineEmits(['hide', 'report', 'create', 'timePointChange']);
// 方法

const onOversize = (file) => {
  $toast.warning(`文件大小不能超过${ maxPhotoSize.value / 1024 / 1024 }Mb`);
};

const beforeRead = (file) => {
  return beforePicUpload(file);
};

const afterRead = (file) => {
  if(file.length>0){
   file.forEach((item)=>{
    uploadFunction(item)
   })
  }

};
const uploadFunction=(file)=>{
  console.log("-> file", file);
  file.status = 'uploading';
  file.message = '上传中...';
  let url = props.mainServer.serverDomain + $api.basics.content_server_url();
  url = url.replace(/\?.*/, '');
  $api.basics.newUpload(url, file).then(res => {
    let url = res.domainPrefix + res.fileContentUrl;
    file.status = 'success';
    file.message = '上传成功';
    file.storageId = res.storageId;
    file.url = url;
    fileList.value.push({ url: url, storageId: res.storageId });
  }).catch((err) => {
    $toast.fail('上传失败');
  });
}
const save = () => {
try{
  if (content.value.trim() !== "" || !props.showInput) {
    let params = {};
    if (props.type === '1') {
      params.appraiseContent = content.value;
      params.isAnonymous = isAnonymous.value ? 1 : 2;
      params.appraiseScore = score.value;
    } else if (props.type === '2') {
      params.content = content.value;
      params.isAnonymous = isAnonymous.value ? 1 : 2;
      params.imageUrl = fileList.value.map(item => item.storageId).join(',');
    } else if (props.type === '3') {
      params.content = content.value;
      params.isPublic = isPublic.value ? 1 : 2;
      params.learnTime = isTimePoint.value ? props.noteTime : "";
    } else if (props.type === '4') {
      params.appraiseScore = score.value;
    } else if (props.type === '5') {
      params.content = content.value;
    }
    if (props.type === '5') {
      emit("report", params);
    } else {
      emit("create", params);
    }
  } else {
    $toast.warning("请填写内容");
  }
}catch(e){
 let content= sm2.doEncrypt(`${e}------------ACtionConfirm.vue`, MS2_PUBLICKEY, cipherMode)
  $api.sys.logRecode({
    logs:content
  })
}
};

const timePointChange = (val) => {
  if (val) {
    emit("timePointChange");
  }
};
</script>

<style lang="scss" scoped>
	.bottomActionConfig{
		z-index: 999999;
	}
.com-appraise-wrap {
  padding: 20px 15px 40px;
  //text-align: center;
  .wrap-title {
    font-size: 16px;
    line-height: 22px;
    margin-bottom: 10px;
  }
  .form-wrap {
    .form-field {
		align-items: center;
      :deep(.van-rate__icon) {
        margin-right: 8px;
      }
    }
    textarea {
      padding: 10px;
      width: 100%;
      background: #f6f6f6;
      // border: 1PX solid #EEEEEE;
    }
  }
  .btn-wrap {
    padding: 0 20px;
    button {
      width: 100%;
      height: 40px;
    }
  }
  .video-area {
    font-size: 14px;
    margin-left: 10px;
    line-height: 21px;
    .video-icon {
      width: 8px;
      height: 8px;
      vertical-align: 1px;
      margin-right: 5px;
      display: inline-block;
      &.dark {
        background: url("");
      }
    }
  }
  .upload {
    .van-field__control {
      width: 100%;
      height: auto;
      text-indent: 0;
      background: none;
      border: none;

      .van-uploader {
        .van-uploader__preview {
          width: 30%;
          margin-right: 10px;
        }

        .van-image {
          width: 100%;
          height: 108px;
        }
      }

      .van-uploader__upload {
        width: 108px;
        height: 108px;
        margin-right: 0;
        background: #FFFFFF;
        border-radius: 4px;
        border: 1px solid #EEEEEE;
      }
    }
  }
}
</style>
